<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/2/26
 * Time: 15:33
 */

namespace We7\Dev\DebugBar\W7;


use DebugBar\DataCollector\PDO\TraceablePDO;
use PDO;
use PDOException;

class W7TraceablePDO extends TraceablePDO
{

	public function __construct(PDO $pdo)
	{
		$this->pdo = $pdo;
        $this->pdo->setAttribute(PDO::ATTR_STATEMENT_CLASS, array('We7\Dev\DebugBar\W7\W7TraceablePDOStatement', array($this)));
	}
	/**
	 * Profiles a call to a PDO method
	 *
	 * @param  string $method
	 * @param  string $sql
	 * @param  array  $args
	 * @return mixed  The result of the call
	 */
	protected function profileCall($method, $sql, array $args)
	{

		$trace = new W7TracedStatement($sql);
		$trace->start();

		$ex = null;
		try {
			$result = call_user_func_array(array($this->pdo, $method), $args);
		} catch (PDOException $e) {
			$ex = $e;
		}

		if ($this->pdo->getAttribute(PDO::ATTR_ERRMODE) !== PDO::ERRMODE_EXCEPTION && $result === false) {
			$error = $this->pdo->errorInfo();
			$ex = new PDOException($error[2], $error[0]);
		}

		$trace->end($ex);
		$this->addExecutedStatement($trace);

		if ($this->pdo->getAttribute(PDO::ATTR_ERRMODE) === PDO::ERRMODE_EXCEPTION && $ex !== null) {
			throw $ex;
		}
		return $result;
	}

}